<?php

/**
 *  +----------------------------------------------------------------------
 *  | 文件功能：CategoryController.php：栏目分类相关操作
 *  +----------------------------------------------------------------------
 *  | Copyright (c) 2022~2024 https://www.huihuiv.com All rights reserved. 
 *  +----------------------------------------------------------------------
 *  | Create At: 2024年03月05日 00:15:12
 *  +----------------------------------------------------------------------
 *  | Author: 半壶水 <star@cqshanwen.com>
 *  +----------------------------------------------------------------------
 */


namespace App\Http\Controllers\Api;

use App\Interface\CurdController;
use App\Librarys\Message;
use App\Librarys\Sort;
use App\Models\CategoryModel;
use App\Models\ContentModel;
use App\Models\ContentSimpleModel;
use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class CategoryController extends BaseController implements CurdController
{
    protected Request $request;
    protected Model $categoryModel;
    protected Model $contentSimpleModel;

    public function __construct(Request $request, CategoryModel $categoryModel, ContentSimpleModel $contentSimpleModel)
    {
        $this->request = $request;
        $this->categoryModel = $categoryModel;
        $this->contentSimpleModel = $contentSimpleModel;
    }

    /**
     * 新增/修改分类
     *
     * @return JsonResponse
     */
    public function create(): JsonResponse
    {
        // 获取必要参数
        $flag = $this->request->flag;
        $category['pid'] = $this->request->pid;
        $category['status'] = $this->request->status;
        $category['title'] = $this->request->title;
        $category['is_hidden'] = $this->request->is_hidden;
        $category['type'] = $this->request->type;
        $category['thumbnail'] = $this->request->thumbnail;
        $category['description'] = $this->request->description;
        $category['router_link'] = $this->request->router_link;

        // 判断新增还是修改
        switch ($flag) {
            default:
                Message::show(false, '未定义操作');
                break;
            case 'create': // 新增
                // 验证数据
                $validate = Validator::make($category, [
                    'pid' => 'required',
                    'title' => 'required|unique:sw_category',
                    'is_hidden' => 'required',
                    'type' => 'required',
                ], [
                    'pid.required' => '分类归属错误',
                    'title.required' => '分类名称不能为空',
                    'title.unique' => '分类已经存在',
                    'is_hidden.required' => '分类是否显示未定义',
                    'type.required' => '分类类型未定义',
                ]);

                // 判断验证是否成功
                if ($validate->fails()) {
                    // 验证失败
                    return Message::show(false, $validate->errors()->first());
                }

                // 验证成功，开启事务
                DB::beginTransaction();
                try {
                    // 尝试写入
                    $this->categoryModel->create($category);
                    // 提交事务
                    DB::commit();
                    return Message::show(true, '分类创建成功');
                } catch (Exception $error) {
                    // 事务回滚
                    DB::rollBack();
                    return Message::show(false, $error->getMessage());
                }
                break;
            case 'update': // 修改分类
                // 获取修改必要参数
                $cid = $this->request->cid;
                if ((int)$cid < 1) {
                    return Message::show(false, '参数非法');
                }
                // 验证数据
                $validate = Validator::make($category, [
                    'status' => 'required',
                    'title' => 'required',
                    'pid' => 'required',
                    'is_hidden' => 'required',
                    'type' => 'required'
                ], [
                    'status.required' => '分类状态不能为空',
                    'title.required' => '分类名称不能为空',
                    'pid.required' => '分类归属不能为空',
                    'is_hidden.required' => '分类是否可视',
                    'type.required' => '分类类型不能为空'
                ]);

                // 开启事务
                DB::beginTransaction();
                try {
                    // 尝试修改数据库
                    $this->categoryModel->where(['cid' => $cid])->update($category);
                    // 提交事务
                    DB::commit();
                    return Message::show(true, '分类信息修改成功');
                } catch (Exception $error) {
                    // 事务回滚
                    DB::rollBack();
                    return Message::show(false, $error->getMessage());
                }
                break;
        }
    }

    /**
     * 获取分类数据
     *
     * @return JsonResponse
     */
    public function query(): JsonResponse
    {
        // 获取操作标识符
        $flag = $this->request->flag;

        // 匹配操作
        switch ($flag) {
            default:
                return Message::show(false, '未定义操作');
                break;
            case 'table': // 获取表格数据格式
                // 获取所有分类
                $categoryList = $this->categoryModel->get();
                // 生成分类树
                $categoryTree = Sort::build_category_tree(0, $categoryList);
                return Message::show(true, '获取成功', $categoryTree);
                break;
            case 'usable': // 获取可发布内容栏目数据
                // 获取分类
                $category = $this->categoryModel->where(['usable' => 0])->get();
                return Message::show(true, '获取成功', $category);
                break;
        }
    }

    public function delete(): JsonResponse
    {
        // 获取必要参数
        $cid = $this->request->cid;
        // 判断
        if ((int)$cid < 1) {
            return Message::show(false, '非法参数');
        }
        // 判断是否还有相关文章归属
        if ($this->contentSimpleModel->where(['cid' => $cid])->exists()) {
            return Message::show(false, '该分类下还有内容，无法删除');
        }
    }
}
